<template>
  <div class="register-page">
    <el-card class="register-card">
      <h2 class="register-title">注册 AI Chat</h2>
      <p class="register-subtitle">{{ subtitle }}</p>
      <el-form class="register-form" @submit.prevent="handleRegister">
        <el-form-item label="用户名">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            autocomplete="username"
            :disabled="loading || !registrationEnabled"
          />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input
            v-model="form.nickname"
            placeholder="请输入昵称（可选）"
            :disabled="loading || !registrationEnabled"
          />
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            autocomplete="new-password"
            :disabled="loading || !registrationEnabled"
          />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            autocomplete="new-password"
            :disabled="loading || !registrationEnabled"
            @keyup.enter="handleRegister"
          />
        </el-form-item>
        <div class="register-actions">
          <el-button
            type="primary"
            :loading="loading"
            :disabled="!registrationEnabled"
            round
            @click="handleRegister"
          >
            注册
          </el-button>
          <el-button
            round
            @click="goToLogin"
          >
            返回登录
          </el-button>
        </div>
        <p v-if="errorMessage" class="error-text">{{ errorMessage }}</p>
        <div class="form-footer">
          <span>已有账号？</span>
          <router-link to="/login" class="login-link">立即登录</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import apiClient from '@/api/api'
import { loadAuthConfig } from '@/services/authService'

const router = useRouter()

const form = reactive({
  username: '',
  nickname: '',
  password: '',
  confirmPassword: ''
})
const loading = ref(false)
const errorMessage = ref('')
const registrationEnabled = ref(true)
const subtitle = ref('创建您的账户')

const handleRegister = async () => {
  if (!registrationEnabled.value) {
    errorMessage.value = '当前环境未开启注册功能'
    return
  }
  const username = form.username.trim()
  if (!username || !form.password) {
    errorMessage.value = '请输入用户名和密码'
    return
  }
  
  if (form.password !== form.confirmPassword) {
    errorMessage.value = '两次输入的密码不一致'
    return
  }
  
  if (form.password.length < 6) {
    errorMessage.value = '密码长度至少为6位'
    return
  }
  
  loading.value = true
  errorMessage.value = ''
  try {
    await apiClient.post('/v1/auth/register', {
      username,
      password: form.password,
      nickname: form.nickname || username
    })
    ElMessage.success('注册成功，请登录')
    router.push('/login')
  } catch (error: any) {
    errorMessage.value = error?.response?.data?.detail || '注册失败，请重试'
  } finally {
    loading.value = false
  }
}

const goToLogin = () => {
  router.push('/login')
}

const initRegistrationStatus = async () => {
  try {
    const config = await loadAuthConfig()
    if (!config.allow_register) {
      registrationEnabled.value = false
      subtitle.value = '当前环境未开放注册，请联系管理员'
      return
    }
    subtitle.value = '创建您的账户'
  } catch (error) {
    console.warn('获取注册配置失败', error)
  }
}

onMounted(() => {
  initRegistrationStatus()
})
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #eef2ff 0%, #dbeafe 100%);
  padding: 24px;
}

.register-card {
  width: 100%;
  max-width: 420px;
  border-radius: 16px;
  box-shadow: 0 40px 80px rgba(15, 23, 42, 0.12);
}

.register-title {
  margin: 0;
  font-size: 24px;
  color: #111827;
  text-align: center;
}

.register-subtitle {
  margin: 8px 0 24px;
  color: #6b7280;
  text-align: center;
}

.register-form {
  margin-top: 16px;
}

.register-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 8px;
}

.error-text {
  margin-top: 12px;
  color: #ef4444;
  text-align: center;
}

@media (max-width: 480px) {
  .register-page {
    padding: 16px;
  }
  
  .register-card {
    max-width: 100%;
  }
  
  .register-title {
    font-size: 20px;
  }
  
  .register-subtitle {
    font-size: 14px;
  }
  
  .register-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .register-actions .el-button {
    width: 100%;
  }
}
</style>